<template>
  <div class="os-main">
    <div style="padding-bottom: 10px;">
      <el-button @click="onAddItem" :disabled="config.mode === 'look'">添加一行</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="config.mode === 'look'">提交</el-button>
      <el-button type="primary" @click="openJson">查看表单数据</el-button>
      <el-button type="primary" @click="switchMode">切换模式</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>

    <ConfigTableForm v-model="linesData" :config="config" ref="configTableFormRef" />

    <el-drawer v-model="drawerVisiable" title="数据视图" :direction="'rtl'" size="40%">
      <CodeView :code-json="JSON.stringify(linesData, null, '\t')"></CodeView>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import ConfigTableForm from '@/components/ConfigTableForm'
import CodeView from '@/components/CodeView/index.vue'
import type { Config } from '@/components/ConfigTableForm/src/type'
import { ref } from 'vue';

// ConfigTableForm绑定对象
const linesData = ref<ObjectAny[]>([{ username: '' }])
// ConfigTableForm配置
const config = ref<Config>({
  mode: 'add',
  columns: [{
    prop: 'username', // 绑定对象的键
    label: '用户名', // 显示label
    value: 'admin', // 初始值，在绑定的对象prop为 '' 或 null 或 undefined 时默认赋此值
    type: 'input', // 表单元素类型，参考 FormType
    rules: [{ required: true }], // 表单元素校验规则
  }, {
    prop: 'introduce',
    label: '介绍',
    type: 'input',
  }, {
    prop: 'sex',
    label: '性别',
    type: 'select',
    options: [{
      label: '男',
      value: 'man'
    }, {
      label: '女',
      value: 'woman'
    }],
    columnProps: {
      width: 200
    },
    events: {
      'update:modelValue'(val: string, scope: any) { // events所有方法最后一位参数都有scope
        scope.row.idCardEndNum = null // 使用scope操作同一行其他元素
      },
    },
  }, {
    prop: 'idCardEndNum',
    label: '身份证号最后一位',
    type: 'select',
    props: {
      vScope_disabled: (scope: any) => !scope.row.sex, // 属性前添加vScope_前缀，把普通属性转为函数return属性
      // filterable: true,
      vScope_filterMethod: (scope: any) => { // 函数属性同理可用（注意写法，原本就是函数属性，添加vScope_前缀后需要函数return函数属性）
        return (query: string) => {
          console.log(query, scope.row);
          return false
        }
      },
    },
    options: (scope: any) => { // select的options可以直接使用函数形式，接收scope参数返回处理后的选项
      if (scope.row.sex === 'man') return Array.from({ length: 10 }, (_, index) => ({ label: index, value: index })).filter(item => (item.value + 1) % 2 === 0)
      else if (scope.row.sex === 'woman') return Array.from({ length: 10 }, (_, index) => ({ label: index, value: index })).filter(item => item.value % 2 === 0)
      return []
    },
    columnProps: {
      width: 200
    },
  }, {
    prop: 'status',
    label: '状态',
    type: 'switch',
    value: true,
    columnProps: {
      width: 180,
      align: 'center'
    },
    props: {
      inlinePrompt: true,
      activeText: "启用",
      inactiveText: "禁用",
      style: { '--el-switch-on-color': '#13ce66', '--el-switch-off-color': '#ff4949' }
    },
  }]
})

// 提交
const btnLoading = ref(true)
const configTableFormRef = ref()
const onSubmit = async () => {
  let submitFlag = true
  btnLoading.value = true
  const valid = await configTableFormRef.value.mainRef.validate().catch((err: any[]) => err)
  if (valid !== true && submitFlag) {
    // configTableFormRef.value.mainRef.validateField(Object.keys(valid)[0]) // 重新校验首个错误元素
    configTableFormRef.value.$el.querySelector('.is-error .el-input__inner').focus() // 聚焦首个错误元素
    submitFlag = false
    ElMessage.closeAll()
    ElMessage.error('校验失败')
  }

  if (submitFlag) {
    ElMessage.closeAll()
    ElMessage.success('校验成功')
    console.log(linesData)
  } else {
    btnLoading.value = false
  }
}


const onAddItem = () => {
  // now.setDate(now.getDate() + 1)
  linesData.value.push({})
}

// 取消
const onCancel = () => {
  configTableFormRef.value.mainRef.clearValidate()
}

// 重新渲染ConfigForm
const reRenderC = () => {
  configTableFormRef.value.reRender()
}

// 切换ConfigForm展示模式
const switchMode = () => {
  if (config.value.mode === 'add') {
    config.value.mode = 'look'
    configTableFormRef.value.mainRef.clearValidate()
  } else config.value.mode = 'add'
  ElMessage.closeAll()
  ElMessage.success(`当前模式：${config.value.mode}`)
}

// 数据视图
const drawerVisiable = ref(false)
const openJson = () => {
  drawerVisiable.value = true
}
</script>